try:
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *
    from PyQt5.QtWidgets import *
except ImportError:
    from PyQt4.QtGui import *
    from PyQt4.QtCore import *

import time
import datetime
import json
import cv2
import numpy as np
import os
import moviepy.editor as mpe
from moviepy.editor import VideoFileClip
import _thread

from libs.utils import newIcon

BB = QDialogButtonBox

class Worker(QThread):
    progressBarValue = pyqtSignal(int)
    listValue = pyqtSignal(str)
    endsignal = pyqtSignal(int, str)
    handle = 0
    
    def __init__(self, parent, outter, outfilename):
        super(Worker, self).__init__()
        self.parent = parent
        self.outter = outter
        self.outfilename = outfilename
        self.setStackSize(1024*1024)
        
    def run(self):
        pindex = -1
        i = 0
        cimage = None
        maxframe = (self.parent.videoLength // 40 + 1) * 40
        while i < maxframe:
            index = self.parent.getIndex(i)
            if index == pindex:
                pass
            else:
                if index < self.parent.lrc_list.count():
                    imgpath = self.parent.lrc_list.item(index).toolTip()
                    text = self.parent.lrc_list.itemWidget(self.parent.lrc_list.item(index)).findChildren(QLineEdit)[1].text()
                    cimage = self.parent.imageShowOnLabel(imgpath, lrc=text, back=True)
                    self.listValue.emit(text)
                pindex = index
            i += 40
            self.outter.write(cimage)
            self.progressBarValue.emit(i * 1.0 / maxframe * 50)
        self.outter.release()
        self.progressBarValue.emit(50)
        self.listValue.emit("中间文件生成")
        my_clip = VideoFileClip(self.outfilename)
        audio_clip = mpe.AudioFileClip(self.parent.songFileName)
        videolen = my_clip.duration
        audiolen = audio_clip.duration
        while audiolen < videolen:
            audio_clip = mpe.concatenate_audioclips([audio_clip,audio_clip])
            audiolen = audiolen * 2
        self.progressBarValue.emit(60)
        self.final_clip = my_clip.set_audio(audio_clip).subclip(0, videolen)
        outfilename = os.path.join(self.parent.default_save_dir, "result.mp4")
        self.listValue.emit("合成视频与音频")
        self.running = True   
        _thread.start_new_thread(self.exportThread, ("thread export", outfilename))
        for i in range(10000):
            self.progressBarValue.emit(min(60+i, 99))
            time.sleep(1)
            if not self.running:
                break
        self.progressBarValue.emit(100)
        self.listValue.emit("文件保存在："+outfilename)
        print("文件保存在：", outfilename)
        self.endsignal.emit(0, "readAll")
        
    def exportThread(self, threadName, outfilename):
        print("new thread start")
        self.final_clip.write_videofile(outfilename)
        self.running = False
        print("new thread end")
        
        
class ExportDialog(QDialog):
    def __init__(self, parent=None, outter=None, outfilename=None, simple=False):
        super(ExportDialog, self).__init__(parent)
        self.outter = outter
        self.setFixedWidth(800)
        self.parent = parent
        self.simple = simple
        self.outfilename = outfilename
        self.pb = QProgressBar()
        self.pb.setRange(0, 100)
        self.pb.setValue(0)
        
        layout = QVBoxLayout()
        layout.addWidget(self.pb)
        self.listWidget = QListWidget(self)
        layout.addWidget(self.listWidget)
        
        self.buttonBox = bb = BB(BB.Ok | BB.Cancel, Qt.Horizontal, self)
        
        bb.button(BB.Ok).setIcon(newIcon('done'))
        bb.button(BB.Cancel).setIcon(newIcon('undo'))
        bb.accepted.connect(self.validate)
        bb.rejected.connect(self.reject)
        layout.addWidget(bb)
        bb.button(BB.Ok).setEnabled(False)
        
        self.setLayout(layout)
        
        self.setWindowModality(Qt.ApplicationModal)
        
        self.thread_1 = Worker(self.parent, outter, outfilename)
        self.thread_1.progressBarValue.connect(self.handleProgressBarSignal)
        self.thread_1.listValue.connect(self.handleListWidgetSingal)
        self.thread_1.endsignal.connect(self.handleEndsignalSignal)
        
        self.time_start = time.time()
        
    def handleProgressBarSignal(self, i):
        self.pb.setValue(i)
        self.setWindowTitle("Generating -- ")
        
    def handleListWidgetSingal(self, i):
        self.listWidget.addItem(i)
        titem = self.listWidget.item(self.listWidget.count() - 1)
        self.listWidget.scrollToItem(titem)
        
    def handleEndsignalSignal(self, i, str):
        if i == 0 and str == "readAll":
            self.buttonBox.button(BB.Ok).setEnabled(True)
            self.buttonBox.button(BB.Cancel).setEnabled(False)
            
    def reject(self):
        print("reject")
        self.thread_1.handle = -1
        self.thread_1.quit()
        while not self.thread_1.isFinished():
            pass
        self.accept()
        
    def validate(self):
        self.accept()
            
    def popUp(self):
        self.thread_1.start()
        return 1 if self.exec_() else None
    
    def closeEvent(self, event):
        print("close")
        self.reject()